package com.gy.mbaselibrary.fragment;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.gy.mbaselibrary.base.BaseFragment;


/**
 * 创建者：高业
 * 邮箱：15234150168@163.com
 * 时间：2018/2/6
 * 描述：
 * 修改人：
 * 修改时间：2018/2/6
 * 修改备注：
 */
public abstract class LazyFragment extends BaseFragment {
    protected boolean isInit;
    protected boolean isVisible;
    protected boolean isFirstLoad;
    protected boolean isAttach;
    protected boolean isResume;
    protected boolean isFirstFragment;
    protected boolean isHidden;
    protected boolean mResu;


    @Override
    public void onAttach(Activity context) {
        super.onAttach(context);
        isAttach = true;
        setMResume();
        setLazyLoadData();
    }

    @Override
    public View onCreateView(LayoutInflater layoutInflater, ViewGroup viewGroup, Bundle bundle) {
        isInit = true;
        isFirstLoad = true;
        return super.onCreateView(layoutInflater, viewGroup, bundle);
    }

    public void setFirstFragment(boolean firstFragment) {
        isFirstFragment = firstFragment;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        isInit = false;
    }



    @Override
    public void onResume() {
        super.onResume();
        isResume = true;

        if (isFirstFragment){
            isVisible = true;
        }
        setMResume();
        setLazyLoadData();

    }

    @Override
    public void onPause() {
        super.onPause();
        isResume = false;
        setMResume();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        isHidden = hidden;
        setMResume();
        setLazyLoadData();

    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        isVisible = !isVisibleToUser;
        setMResume();
        setLazyLoadData();

    }

    public abstract void lazyLoadData();

    protected abstract void mResume();
    protected abstract void mPause();

    private void setMResume(){
        if (isAttach && !isHidden && isResume ){
            if (mResu == false){
                mResume();
                mResu = true;
            }
        }else if (isAttach && (isHidden || !isResume )){
            if (mResu == true){
                mPause();
                mResu = false;
            }

        }
    }

    /*private void setMPause(){
        if (!isVisible && !isAttach && !isResume){
            mPause();
        }
    }*/


    private void setLazyLoadData(){
        if (isFirstLoad && mResu){
            lazyLoadData();
            isFirstLoad = false;
        }
    }
}
